package com.softWang.common.utils.excel.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.softWang.common.base.ExcelEnumCovertInterface;
import com.softWang.common.utils.SpringUtils;
import com.softWang.common.utils.excel.annotation.DictFormat;
import com.softWang.common.utils.excel.annotation.EnumFormat;
import com.softWang.common.utils.excel.dict.DictFrameworkUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * Excel 枚举转换器
 */
@Slf4j
public class EnumConvert implements Converter<Object> {

    @Override
    public Class<?> supportJavaTypeKey() {
        throw new UnsupportedOperationException("暂不支持，也不需要");
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        throw new UnsupportedOperationException("暂不支持，也不需要");
    }

    @Override
    public Object convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        // 使用枚举解析
        Integer value = null;
        // 使用字典格式化
        Class<ExcelEnumCovertInterface> emunClass = getType(contentProperty);
        ExcelEnumCovertInterface[] enumConstants = emunClass.getEnumConstants();
        String label = readCellData.getStringValue();
        if (enumConstants.length > 0) {
            value = enumConstants[0].getJavaValue(label);
        }
        if (value == null) {
            log.error("[convertToJavaData][type({}) 解析不掉 label({})]", emunClass, label);
            return null;
        }
        return value;
    }

    @Override
    public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty,
                                                    GlobalConfiguration globalConfiguration) {
        // 空时，返回空
        if (object == null) {
            return new WriteCellData<>("");
        }
        String label = null;
        // 使用枚举格式化
        Class<ExcelEnumCovertInterface> emunClass = getType(contentProperty);
        ExcelEnumCovertInterface[] enumConstants = emunClass.getEnumConstants();
        if (enumConstants.length > 0) {
            label = enumConstants[0].getExcelLable(Integer.parseInt(String.valueOf(object)));
        }
        if (label == null) {
            log.error("[convertToExcelData][type({}) 转换不了 label({})]", emunClass, object);
            return new WriteCellData<>("");
        }
        // 生成 Excel 小表格
        return new WriteCellData<>(label);
    }

    private static Class getType(ExcelContentProperty contentProperty) {
        return contentProperty.getField().getAnnotation(EnumFormat.class).enumClass();
    }

}
